package edu.cmu.ece.ds.droidchat;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import edu.cmu.ece.ds.droidchat.NetworkService.LocalBinder;
import edu.cmu.ece.ds.droidchat.message.ClientLoginResponseMessage;
import edu.cmu.ece.ds.droidchat.message.ClientRegisterResponseMessage;
import edu.cmu.ece.ds.droidchat.model.StringConstants;
import edu.cmu.ece.ds.droidchat.model.UserInfo;
import edu.cmu.ece.ds.droidchat.model.UserInfo.Availability;
import edu.cmu.ece.ds.droidchat.preference.ColorPreference;
import edu.cmu.ece.ds.droidchat.util.Toolbox;
import edu.cmu.ece.ds.droidchat.widget.QuickActionList;

public class RegisterActivity extends Activity {
    private final String TAG = "RegisterActivity";
    private final int SELECT_IMAGE = 0;

    // Layout Views
    private Button mRegisterButton;
    private TextView mUsernameTextView;
    private EditText mNicknameEditText;
    private ImageView mProfilePictureImageView;
    private TextView mPreviewTextView;
    private QuickActionList quickActionlist;

    // register contents
    private String mUsername;
    private String mPassword;
    private String mNickname;
    private static Drawable mProfilePicture = null;

    private ColorPreference pref;
    private boolean rememberMe;
    private UserInfo userInfo;
    private String profilePicturePath;

    private NetworkService mService; // the Service component
    private boolean mBound = false;

    private ServerMessageReceiver mReceiver; // the BroadcastReceiver component

    // Progress Dialog
    private boolean isLoggingIn = false;
    private boolean isRegistering = false;
    private static final int LOGIN = 0;
    private static final int REGISTER = 1;

    public class ServerMessageReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent);
            String username = intent
                    .getStringExtra(StringConstants.EXTRA_USERNAME);
            int response = intent
                    .getIntExtra(StringConstants.EXTRA_RESPONSE, 0);
            Log.d(TAG, "username: " + username);
            Log.d(TAG, "response: " + response);

            if (isLoggingIn) {
                Log.e(TAG, "isLoggingIn");
                // dismissDialog(LOGIN);

                if (rememberMe) {
                    LogInActivity.saveLoginInfo(RegisterActivity.this,
                            mUsername, mPassword);
                }
                if (response == ClientLoginResponseMessage.LOGIN_SUCCESSFUL) {
                    // successful login
                    // Toolbox.setMyInfo(userInfo);
                    /*
                     * LogInActivity.startDroidChatTabActivity(RegisterActivity.this
                     * , mUsername);
                     */
                    Log.d(TAG, "calling finish()");
                    finish();
                }
            } else if (isRegistering) {
                // register_dialog.dismiss();
                Log.e(TAG, "isRegistering");
                dismissDialog(REGISTER);
                if (response == ClientRegisterResponseMessage.REGISTER_SUCCESSFUL) {
                    isLoggingIn = true;
                    Toast.makeText(
                            RegisterActivity.this,
                            getText(R.string.registration_success_login_1)
                                    + username
                                    + getText(R.string.registration_success_login_2),
                            Toast.LENGTH_LONG).show();
                    Log.e(TAG, "calling log in");
                    mService.login(mUsername, mPassword);
                } else {
                    Toast.makeText(
                            getApplicationContext(),
                            getText(R.string.registration_not_success_1)
                                    + username
                                    + getText(R.string.registration_not_success_2),
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = this.getIntent();
        mUsername = i.getStringExtra(StringConstants.EXTRA_USERNAME);
        mPassword = i.getStringExtra(StringConstants.EXTRA_PASSWORD);
        mNickname = i.getStringExtra(StringConstants.PREF_KEY_NICKNAME);
        rememberMe = i.getBooleanExtra(StringConstants.PREF_KEY_REMEMBER_ME,
                false);
        setContentView(R.layout.registration);
        mRegisterButton = (Button) findViewById(R.id.register_button);
        mUsernameTextView = (TextView) findViewById(R.id.register_email);
        mUsernameTextView.setText(mUsername);
        mNicknameEditText = (EditText) findViewById(R.id.register_nickname);
        mProfilePictureImageView = (ImageView) findViewById(R.id.register_profile_picture);
        mPreviewTextView = (TextView) findViewById(R.id.register_text_bg);

        // restore nickname
        if (savedInstanceState != null) {
            String nickname = savedInstanceState
                    .getString(StringConstants.PREF_KEY_NICKNAME);
            if (nickname != null) {
                mNicknameEditText.setText(nickname);
            }
        } else if (mNickname != null) {
            mNicknameEditText.setText(mNickname);
        }

        // profile picture
        if (mProfilePicture != null) {
            mProfilePictureImageView.setImageDrawable(mProfilePicture);
        } else if (LogInActivity.facebookProfilePicture != null) {
            mProfilePicture = LogInActivity.facebookProfilePicture;
            mProfilePictureImageView.setImageDrawable(mProfilePicture);
        }
        mProfilePictureImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(
                        new Intent(
                                Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI),
                        SELECT_IMAGE);

            }
        });
        // message background color preference
        pref = new ColorPreference(this);
        mPreviewTextView.setBackgroundResource(ColorPreference
                .getMyBackgroundDrawableResId(pref
                        .getMyMessageBackgroundColor()));
        quickActionlist = pref
                .prepareColorPickerQuickActionList(mPreviewTextView);
        mPreviewTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "mPreviewTextView clicked");
                quickActionlist.show();
            }
        });

        // register button
        mRegisterButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Opens Socket to contact the servers
                Log.d(TAG, mUsername);
                Log.d(TAG, mPassword);

                if (mService.isConnectedToServer()) {
                    Log.d(TAG, "TCPService has a connection with server");
                } else {
                    Log.d(TAG,
                            "TCPService does NOT have a connection with server");
                }

                if (validateInput() == true) {

                    if (mBound == true) {
                        if (mService.isConnectedToServer()) {
                            Log.d(TAG, "mBound is true");
                            Log.d(TAG, "nickname is " + mNickname);
                            // asks the service to send ClientRegisterMessage to
                            // the DroidChat server
                            userInfo = new UserInfo(mUsername, mNickname,
                                    mProfilePictureImageView.getDrawable(),
                                    Availability.AVAILABLE, pref
                                            .getMyMessageBackgroundColor());
                            mService.register(userInfo, mPassword);
                            isRegistering = true;
                            showDialog(REGISTER);
                        } else {
                            Toast.makeText(RegisterActivity.this,
                                    R.string.login_error_server_down,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });

        mReceiver = new ServerMessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(StringConstants.ACTION_FOR_REGISTER_ACTIVITY);
        // filter.addAction(StringConstants.ACTION_CLIENT_REGISTER_RESPONSE);
        Log.d(TAG, "ServerMessageReceiver registered! ");
        this.registerReceiver(mReceiver, filter);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "---onStart---");
        Intent intent = new Intent(this, NetworkService.class);
        Log.d(TAG, "calling bindService()");
        Toolbox.bindService(this, intent, mConnection,
                Context.BIND_AUTO_CREATE, TAG);

    }

    // most likely the user pressed back to go back to the LogInActivity
    public void onStop() {
        super.onStop();
        Log.d(TAG, "---onStop---");
        Log.d(TAG, "---calling unbindService---");
        Toolbox.unbindService(this, mConnection, TAG);
        /*
         * Log.d(TAG, "---finishing RegisterActivity---"); finish();
         */
    }

    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "---onDestroy---");
        unregisterReceiver(mReceiver);
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to TCPService, cast the IBinder and get TCPService
            // instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
            Log.d(TAG, "We've bound to TCPService");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    private boolean validateInput() {
        mNickname = mNicknameEditText.getText().toString().trim();
        if (mNickname.length() == 0) {
            Toast.makeText(this, R.string.register_error_nickname_not_entered,
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    protected Dialog onCreateDialog(int id) {
        ProgressDialog dialog;
        switch (id) {
        case LOGIN:
            dialog = new ProgressDialog(RegisterActivity.this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage(RegisterActivity.this
                    .getText(R.string.login_wait));
            break;
        case REGISTER:
            dialog = new ProgressDialog(this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage(this.getText(R.string.register_wait));
            break;
        default:
            dialog = null;
        }
        // login_dialog = dialog;
        return dialog;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(StringConstants.PREF_KEY_NICKNAME, mNicknameEditText
                .getText().toString());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE) {
            if (resultCode == RESULT_OK) {
                Uri photoUri = data.getData();

                if (photoUri != null) {
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                                this.getContentResolver(), photoUri);

                        Log.e(TAG,
                                "bitmap " + bitmap.getWidth() + ","
                                        + bitmap.getHeight());

                        int newWidth, newHeight;
                        double ratio = (double) bitmap.getWidth()
                                / bitmap.getHeight();
                        if (ratio >= 1) {
                            newWidth = 60;
                            newHeight = (int) (60 / ratio);
                        } else {
                            newWidth = (int) (60 / ratio);
                            newHeight = 60;
                        }
                        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth,
                                newHeight, true);
                        mProfilePictureImageView.setImageBitmap(bitmap);
                        mProfilePicture = mProfilePictureImageView
                                .getDrawable();
                        Log.e(TAG, "mProfilePicture=" + mProfilePicture);
                        profilePicturePath = photoUri.toString();
                    } catch (OutOfMemoryError e) {
                        Toast.makeText(this, R.string.out_of_memory,
                                Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // restore the original picture
        mProfilePicture = null;
    }

}
